package com.leo.m1803.d06;

/**
 * Created by LEO on 2018/3/6.
 */
public class Kmp {
    private static int[] getNext(String p){
        int[] next = new int[p.length()];
        int i = 0;
        int j = -1;
        next[0] = -1;
        while (i < p.length()){
            if (j==-1 || p.charAt(i)==p.charAt(j)){
                next[i++] = j++;
            }else {
                j = next[j];
            }
        }
        return next;
    }

    public static int kmp(String s, String p){
        int[] next = getNext(p);
        int i = 0, j = 0;
        while (i<s.length() && j<p.length()){
            if (j == -1 || s.charAt(i)==p.charAt(j)){
                i++;
                j++;
            }else {
                j = next[j];
            }
        }
        if (j == p.length()){
            return i-j;
        }else {
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println(kmp("abababc","abc"));
    }
}
